package com.itema.filter;

import com.itema.utils.CurrentHolder;
import com.itema.utils.JwtUtils;
import io.jsonwebtoken.Claims;
import jakarta.servlet.*;
import jakarta.servlet.annotation.WebFilter;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.io.IOException;

@WebFilter("/*")
public class TokenFilter implements Filter {
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;

        //1.获取到请求路径
        String path = request.getRequestURI();

        //2.判断当前请求是否为登录请求，如果路径中包含"/login",说明是登陆操作，放行
        if(path.contains("/login")){
            filterChain.doFilter(request, response);
            return;
        }

        //3.获取请求头中的令牌
        String token = request.getHeader("token");

        //4.判断令牌是否为空，如果为空，说明用户没有登录，返回错误信息(401)
        if(token == null || token.isEmpty()){
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            return;
        }

        //5.如果token存在，校验令牌parseToken，如果校验失败，返回错误信息(401)
        try {
            Claims claims = JwtUtils.parseToken(token);
            Integer empId = Integer.valueOf(claims.get("id").toString());
            CurrentHolder.setCurrentId(empId);
        } catch (Exception e) {
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            return;
        }

        //6.校验通过，放行
        filterChain.doFilter(request, response);

        //7.请求处理完毕，清理当前线程的绑定数据
        CurrentHolder.remove();


    }
}
